package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-note-sys/cache"
	"red-note-sys/model"
	"strconv"
	"time"
)

func Release(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	author := c.PostForm("author")

	if title == "" || comment == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.RedNote{
		Title:   title,
		Comment: comment,
		Author:  author,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "red_note" + strconv.Itoa(int(data.ID))
	var rednote model.RedNote
	model.DB.Where("id=?", data.ID).First(&rednote)
	jsonData, _ := json.Marshal(rednote)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")

	err := model.DB.Where("id=?", id).Delete(&model.RedNote{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "red_note" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var rednote []model.RedNote
	model.DB.Find(&rednote)

	redis_key := "rednote_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&rednote)
		jsonData, _ := json.Marshal(rednote)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &rednote)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示列表成功",
		"data": rednote,
	})
	return

}
